<?php
namespace app\common\controller;
use app\admin\service\EchartsService;
use app\admin\service\ReportService;
use app\BaseController;
use app\model\FollowUserModel;
use app\model\RatingScaleFactorLevelModel;
use app\model\RatingScaleFactorWarningModel;
use app\model\RatingScaleModel;
use app\model\TaskFactorScoreModel;
use app\model\TaskModel;
use app\model\TaskRatingScaleModel;
use app\model\TaskUserResultModel;
use app\model\WarningReportRecordModel;
use think\App;

class RestoreData extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function index($rating_scale_id): bool|string
    {
        try {
            $TaskUserResultModel = new TaskUserResultModel();
            $FollowUserModel = new FollowUserModel();
            $TaskFactorScoreModel = new TaskFactorScoreModel();
            $data = $TaskUserResultModel->where('rating_scale_id','=',$rating_scale_id)->select()->toArray();
            //因子
            $RatingScaleModel = new RatingScaleModel();
            $RatingScaleInfo = $RatingScaleModel->find($rating_scale_id);
            if (!$RatingScaleInfo) throw new \Exception('参数错误！'.$RatingScaleInfo);
            $RatingScaleFactorLevelModel = new RatingScaleFactorLevelModel();
            $levelList = $RatingScaleFactorLevelModel->where([
                ['rating_scale_id', '=', $rating_scale_id],
                ['mode_id', '=', $RatingScaleInfo['mode_id']],
            ])->field('id,factor_id,level,low_range,high_range')->select()->toArray();
            $levelData = [];
            foreach ($levelList as $level) {
                $levelData[$level['factor_id']][] = $level;
            }
            $RatingScaleFactorWarningModel = new RatingScaleFactorWarningModel();
            $factorWarningList = $RatingScaleFactorWarningModel->where([
                ['rating_scale_id', '=', $rating_scale_id],
                ['mode_id', '=', $RatingScaleInfo['mode_id']],
            ])->field('id,factor_id,condition1_level')->select()->toArray();
            $factorWarningData = [];
            foreach ($factorWarningList as $factorWarning) {
                $factorWarningData[$factorWarning['factor_id']][] = $factorWarning;
            }
            foreach ($data as $value) {
                $factorScoreUpdate = [];
                //先删除关注
                $FollowUserModel->where([
                    ['channel','=',2],
                    ['channel_id','=',$value['id']]
                ])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $factorScore = $TaskFactorScoreModel->where('result_id','=',$value['id'])->with([
                    'TeamRatingScaleFactor'
                ])->select()->toArray();
                $isWarning = 0;
                $warningId = 0;
                $condition1_level = 0;
                $warning_factor_id = 0;
                foreach ($factorScore as $v) {
                    $factor_level_id = 0;
                    foreach ($levelData[$v['factor_id']] as $level) {
                        if ($v['score'] >= $level['low_range'] && $v['score'] <= $level['high_range']) {
                            $factor_level_id = $level['id'];
                            if ($level['level'] > 1) {
                                if ($v['factor_name'] == '总分'){
                                    foreach ($factorWarningData[$v['factor_id']] as $WarningInfo) {
                                        if ($WarningInfo['condition1_level'] == $level['level'] && $condition1_level <= $WarningInfo['condition1_level']) {
                                            $isWarning = 1;
                                            $warningId = $WarningInfo['id'];
                                            $warning_factor_id = $v['factor_id'];
                                            $condition1_level = $WarningInfo['condition1_level'];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $factorScoreUpdate[] = [
                        'id' => $v['id'],
                        'factor_level_id' => $factor_level_id
                    ];
                }
                //更新因子预警等级
                foreach ($factorScoreUpdate as &$update) {
                    $update['is_warning'] = $isWarning;
                    $update['warning_id'] = $warningId;
                }
                $TaskFactorScoreModel->saveAll($factorScoreUpdate);
                //更新结果
                $TaskUserResultModel->where('id','=',$value['id'])->update([
                    'is_warning' => $isWarning,
                    'warning_id' => $warningId,
                    'warning_factor_id' => $warning_factor_id,
                ]);
                if ($isWarning){
                    //加入关注人群
                    $FollowUserModel->insert([
                        'unit_id' => $value['unit_id'],
                        'operator_uid' => 0,
                        'uid' => $value['uid'],
                        'channel' => 2,
                        'channel_id' => $value['id'],
                        'time' => $value['time'],
                    ]);
                }
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    public function taskWarningNum(): bool|string
    {
        try {
            $TaskUserResultModel = new TaskUserResultModel();
            $TaskModel = new TaskModel();
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskData = $TaskModel->select()->toArray();
            foreach ($TaskData as $value) {
                $warning_num = $TaskUserResultModel->where([
                    ['task_id','=',$value['id']],
                    ['is_warning','=',1]
                ])->count();
                $TaskModel->where('id','=',$value['id'])->update([
                    'warning_num' => $warning_num
                ]);
            }
            $TaskRatingScaleData = $TaskRatingScaleModel->select()->toArray();
            foreach ($TaskRatingScaleData as $value) {
                $warning_num = $TaskUserResultModel->where([
                    ['task_id','=',$value['task_id']],
                    ['is_warning','=',1],
                    ['rating_scale_id','=',$value['rating_scale_id']]
                ])->count();
                $TaskRatingScaleModel->where('id','=',$value['id'])->update([
                    'warning_num' => $warning_num
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function warningReportRecord(): bool|string
    {
        try {
            $WarningReportRecordModel = new WarningReportRecordModel();
            $TaskUserResultModel = new TaskUserResultModel();
            $Resultids = $TaskUserResultModel->where('is_warning','=',0)->column('id');
            $WarningReportRecordModel->where([
                ['source','=',1],
                ['result_id','in',$Resultids]
            ])->delete();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务测评报告详情
     * @return bool|string
     */
    public function TaskEvaluationReport(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getTaskReportInfo($id);
            if (empty($data) || $data['admin_del'] == 1) throw new \Exception('报告已被删除！');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }



    public function getResultId(): bool|string
    {
        try {
            $TaskUserResultModel = new TaskUserResultModel();
            $data = $TaskUserResultModel->where([
                ['unit_id','=',31],
                ['word','=','']
            ])->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 生成word任务报告
     * @return bool|string
     */
    public function TaskWord(): bool|string
    {
        try {
            $data = $this->request->param('data');
            $data = json_decode($data, true);
            $TaskUserResultModel = new TaskUserResultModel();
            $info = $TaskUserResultModel->find($data['id']);
            if (!$info) throw new \Exception('参数错误！');
            $EchartsService = new EchartsService($this->app);
            $SelfWord = $EchartsService->SelfWord($data);
            $HospitalWord = $EchartsService->HospitalWord($data);
            $info->save([
                'word' => $SelfWord['word'],
                'pdf' => $SelfWord['pdf'],
                'concise_word' => $HospitalWord['word'],
                'concise_pdf' => $HospitalWord['pdf'],
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}